package what.the.fun.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.*;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import what.the.fun.domain.*;
import what.the.fun.services.UserService;

@Controller
public class LoginController
{

	@Autowired  
	UserService userService;
	
	@RequestMapping("/sigup")
	 public ModelAndView registerUser(@ModelAttribute User user) {
		ModelMap model = new ModelMap();
		return new ModelAndView("user/signup", "model", model);
	 }

	
	 @RequestMapping("/user-insert")
	 public String inserData(@ModelAttribute User user) {
		  if (user != null) {
			  userService.insertData(user);
			  return "redirect:/login";
		  }
		  else {
			  return "redirect:/sigup";
		  }
	 }

	 @RequestMapping("/getList")
	 public ModelAndView getUserLIst() {
	  List<User> userList = userService.getUserList();
	  return new ModelAndView("user-list", "userList", userList);
	 }

	 @RequestMapping("/edit")
	 public ModelAndView editUser(@RequestParam String id,
	   @ModelAttribute User user) {

	  user = userService.getUser(id);

	  Map<String, Object> map = new HashMap<String, Object>();
	  map.put("user", user);

	  return new ModelAndView("user-edit", "map", map);

	 }

	 @RequestMapping("/update")
	 public String updateUser(@ModelAttribute User user) {
	  userService.updateData(user);
	  return "redirect:/getList";

	 }

	 @RequestMapping("/delete")
	 public String deleteUser(@RequestParam String id) {
	  System.out.println("id = " + id);
	  userService.deleteData(id);
	  return "redirect:/getList";
	 }
	 
	 
	 
	 @RequestMapping("/login")
	 public ModelAndView login(HttpSession session, String message) {
		 return new ModelAndView("/user/login");
	 }
	 
	 @RequestMapping("/login-process")
	 public String loginProcess(@RequestParam(value = "username") String name
			 				, @RequestParam(value = "password") String password
			 				, HttpSession session) {
		 User user = userService.checkLogin(name, password);
		 if (user != null) {
			 session.setAttribute("userId", user.getUserId());
			 session.setAttribute("userName", name);
			 session.setAttribute("password", password);
			 return "redirect:/";
		 }
		 else {
			 return "redirect:/login?message=fail";
		 }
	 }
	 
	 @RequestMapping("/logout")
	 public String logout(HttpSession session, String message) {
		 session.removeAttribute("userId");
		 session.removeAttribute("userName");
		 session.removeAttribute("password");
		 return "redirect:/";
	 }
}
